package com.example.job.handler;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.example.core.constants.CacheConstants;
import com.example.core.constants.Constants;
import com.example.job.domain.exam.Exam;
import com.example.job.mapper.exam.ExamMapper;
import com.example.redis.service.RedisService;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;

@Component
public class ExamListHandler {

    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private RedisService redisService;

    //每天凌晨整理竞赛列表
    @XxlJob("examListOrganizeHandler")
    @Transactional(rollbackFor = Exception.class)
    public void examListOrganizeHandler() {
        LocalDateTime now = LocalDateTime.now();
        //查看未结束的竞赛列表
        List<Exam> notStartExamList = examMapper.selectList(new LambdaQueryWrapper<Exam>()
                .select(Exam::getExamId)
                .gt(Exam::getEndTime, now)
                .eq(Exam::getStatus, Constants.TRUE)
                .orderByDesc(Exam::getStartTime));
        redisService.deleteObject(getExamListKey());
        if (!CollectionUtils.isEmpty(notStartExamList)) {
            List<Long> notStartExamIdList = notStartExamList.stream().map(Exam::getExamId).toList();
            redisService.rightPushAll(getExamListKey(), notStartExamIdList);
        }

        //查看已经结束的竞赛
        List<Exam> endedExamList = examMapper.selectList(new LambdaQueryWrapper<Exam>()
                .select(Exam::getExamId)
                .lt(Exam::getEndTime, now)
                .eq(Exam::getStatus, Constants.TRUE)
                .orderByDesc(Exam::getEndTime));
        redisService.deleteObject(getHistoryListKey());
        if (!CollectionUtils.isEmpty(endedExamList)) {
            List<Long> endedExamIdList = endedExamList.stream().map(Exam::getExamId).toList();
            redisService.rightPushAll(getHistoryListKey(), endedExamIdList);
        }
    }

    private String getExamListKey() {
        return CacheConstants.EXAM_NOT_STARTED_LIST;
    }

    private String getHistoryListKey() {
        return CacheConstants.EXAM_HISTORY_LIST;
    }
}
